package cog.support.util.common;

/**
 * 执行耗时工具
 *
 * @author 陈杰
 * @since 2018/3/24 0024 17:44
 * <p>
 * Copyright ChenJie(wuzhiyun@aliyun.com)
 */
public class TimeConsuming {

    /**
     * 时间计数
     * */
    private long[] timeConsuming;


    /**
     * 标题
     * */
    private String[] title;

    /**
     * 当前计数的下标
     * */
    private int currentIndex;


    private long timeMark = 0;

    private String markTitle = "";


    public TimeConsuming(int maxCount){
        this.timeConsuming = new long[maxCount];
        this.title = new String[maxCount];
        this.currentIndex = 0;
    }


    /**
     * 标记时间开始
     * */
    public void mark(String title){
        if(timeMark > 0){
            this.timeConsuming[this.currentIndex++] = System.currentTimeMillis() - timeMark;
            this.title[this.currentIndex - 1] = markTitle;
        }
        this.timeMark = System.currentTimeMillis();
        this.markTitle = title;
    }

    public void println(){
        StringBuilder stringBuilder = new StringBuilder("----------------------------------------------------------------------------------\r\n");
        for(int i =0;i<this.timeConsuming.length;i++){
            if(StringKit.isNotEmpty(this.title[i]))
            stringBuilder.append("  >").append(StringKit.rightPad(this.title[i],10," ") ).append(" = ").append(this.timeConsuming[i]).append("\r\n");
        }
        stringBuilder.append("----------------------------------------------------------------------------------");
        System.out.println(stringBuilder);
    }


    public static void main(String[] args) throws InterruptedException {
        TimeConsuming timeConsuming = new TimeConsuming(10);
        timeConsuming.mark("1111");
        Thread.sleep(1000L);
        timeConsuming.mark("2222");
        Thread.sleep(6000L);
        timeConsuming.mark("3333");
        Thread.sleep(3000L);
        timeConsuming.mark("4444");
        Thread.sleep(4000L);
        timeConsuming.mark("5555");
        Thread.sleep(2000L);
        timeConsuming.mark("6666");
        timeConsuming.println();

    }


}
